package com.xj.storage.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

public class AliyunCloudStorageService extends CloudStorageService{

    private OSSClient client;


    public AliyunCloudStorageService(CloudStorageConfig config) {
        this.config = config;

        //初始化
        init();
    }

    private void init() {
        client = new OSSClient(config.getEndpoint(), config.getAccessKey(),
                config.getSecretKey());
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), getPath(config.getPrefix(),path));
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            client.setBucketAcl(config.getBucket(), CannedAccessControlList.PublicRead);
            client.putObject(config.getBucket(), path, inputStream);
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败，请检查配置信息", e);
        }

        return config.getDomain() + "/" + path;
    }

    @Override
    public String upload(byte[] data) {
        return upload(data, getPath(config.getPrefix(),""));
    }

    @Override
    public String upload(InputStream inputStream) {
        return upload(inputStream, getPath(config.getPrefix(),""));
    }
}

